package com.chj.comp.common.core.util;

import com.chj.comp.common.core.config.MinioProp;
import io.minio.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author ：cuihui
 * @date ：Created in 2023/1/12
 * @description：minio工具类
 * @modified By：
 */
@Slf4j
@Component
public class MinioUtil {
    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProp minioProp;

    /**
     * 创建bucket
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    private void createBucket(String bucketName) {
        if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            // 设置桶规则（可以先在web端设置，使用client.getBucketPolicy方法获取json字符串）
            String config = "{\n" +
                    "\t\"Version\": \"2012-10-17\",\n" +
                    "\t\"Statement\": [{\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:ListBucketMultipartUploads\", \"s3:GetBucketLocation\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::"+ bucketName +"\"]\n" +
                    "\t}, {\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:ListBucket\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::"+ bucketName +"\"],\n" +
                    "\t\t\"Condition\": {\n" +
                    "\t\t\t\"StringEquals\": {\n" +
                    "\t\t\t\t\"s3:prefix\": [\"a\", \"r\"]\n" +
                    "\t\t\t}\n" +
                    "\t\t}\n" +
                    "\t}, {\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:GetObject\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::"+ bucketName +"/r*\"]\n" +
                    "\t}, {\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:AbortMultipartUpload\", \"s3:DeleteObject\", \"s3:ListMultipartUploadParts\", \"s3:PutObject\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::"+ bucketName +"/w*\"]\n" +
                    "\t}, {\n" +
                    "\t\t\"Effect\": \"Allow\",\n" +
                    "\t\t\"Principal\": {\n" +
                    "\t\t\t\"AWS\": [\"*\"]\n" +
                    "\t\t},\n" +
                    "\t\t\"Action\": [\"s3:AbortMultipartUpload\", \"s3:DeleteObject\", \"s3:GetObject\", \"s3:ListMultipartUploadParts\", \"s3:PutObject\"],\n" +
                    "\t\t\"Resource\": [\"arn:aws:s3:::"+ bucketName +"/a*\"]\n" +
                    "\t}]\n" +
                    "}";
            client.setBucketPolicy(SetBucketPolicyArgs.builder()
                    .bucket(bucketName)
                    .config(config)
                    .build());
        }
    }

    /**
     * 上传文件
     *
     * @param bucketName 存储桶
     * @param prefix 文件前缀
     * @param file 文件
     * @return
     */
    public Result uploadFile(String bucketName, String prefix, MultipartFile file){
        // 判断上传文件是否为空
        if (null == file || 0 == file.getSize()) {
            return Result.failed("上传文件不能为空");
        }
        try {
            // 判断存储桶是否存在
            createBucket(bucketName);
            // 文件名
            String originalFilename = file.getOriginalFilename();
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String fileName = prefix + "/" + bucketName + "_" + System.currentTimeMillis() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 开始上传
            client.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
            return Result.ok(minioProp.getEndpoint() + "/" + bucketName + "/" + fileName, null);
        }  catch (Exception e) {
            log.error("上传文件失败：{}", e.getMessage());
        }
        return Result.failed("上传文件失败");
    }

    /**
     * 删除文件
     *
     * @param bucketName 存储桶
     * @param fileName 文件名称
     * @return
     */
    public Result deleteFile(String bucketName, String fileName){
        try {
            // 判断存储桶是否存在
            if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                return Result.failed("存储桶不存在");
            }
            // 文件名
            client.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build()
            );
            return Result.ok("删除文件成功");
        }  catch (Exception e) {
            log.error("删除文件失败：{}", e.getMessage());
        }
        return Result.failed("删除文件失败");
    }
}
